package com.lsy.weizhi2.fragment;

import android.app.Fragment;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;


import com.lsy.weizhi2.R;
import com.lsy.weizhi2.adapter.MyAblum_Adapter;
import com.lsy.weizhi2.customview.AutoGridView;
import com.lsy.weizhi2.myutils.AblumCall;
import com.lsy.weizhi2.picture.BucketDisplay;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 嗨哟 on 2016/12/21.
 */
public class MyAblum_frag_dirs extends Fragment {
    private Context context;
    private View view;
    private AutoGridView myablum_gv;
    private AblumCall ablumCall;
    private List<BucketDisplay> bucketDisplays;
    private MyAblum_Adapter myAblum_adapter;
    private List<BucketDisplay>bucketList;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==1){
                myAblum_adapter.UpData(bucketList);
            }
        }
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ablumCall= (AblumCall) getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view=inflater.inflate(R.layout.ablum,container,false);
        myablum_gv= (AutoGridView) view.findViewById(R.id.myablum_gv);
        return view;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        context=getActivity();
    }

    @Override
    public void onStart() {
        super.onStart();
        new Thread(new Runnable() {
            @Override
            public void run() {
                bucketList=getAlbum();
                handler.sendEmptyMessage(1);
            }
        }).start();
        myAblum_adapter=new MyAblum_Adapter(context,bucketList);
        myablum_gv.setAdapter(myAblum_adapter);
        myablum_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String name=bucketList.get(i).getName();
                int count=bucketList.get(i).getCount();
                ablumCall.Select(name,count);
            }
        });
    }

    private List<BucketDisplay> getAlbum(){
        bucketDisplays=new ArrayList<>();
        ContentResolver cr=context.getContentResolver();
        //String selection="0=0)group by("+ MediaStore.Images.Media.BUCKET_DISPLAY_NAME;
        String selection=MediaStore.Images.Media.MIME_TYPE+"=\"image/jpeg\" or "+MediaStore.Images.Media.MIME_TYPE+"=\"image/png\""+")group by("+ MediaStore.Images.Media.BUCKET_DISPLAY_NAME;
        String[]projection={MediaStore.Images.Media.BUCKET_DISPLAY_NAME,"count(*) as image_count"};
        Cursor cursor=cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,projection,selection,null, MediaStore.Images.Media.DATE_MODIFIED+" desc");
        if(cursor.moveToFirst()){
            do{
                BucketDisplay bucketDisplay=new BucketDisplay();
                String name=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME));
                bucketDisplay.setName(name);
                int count=cursor.getInt(cursor.getColumnIndex("image_count"));
                bucketDisplay.setCount(count);
                String[]projection1={MediaStore.Images.Media._ID,MediaStore.Images.Media.DATA};
                String selection1=null;
                if(TextUtils.isEmpty(name)){
                    //没有传入文件夹名称，查询所有图片信息
                    if(count>0){
                        selection1= MediaStore.Images.Media._ID+"<"+count;
                    }
                }else{
                    selection1= MediaStore.Images.Media.BUCKET_DISPLAY_NAME+"=\""+name+"\" and ("+MediaStore.Images.Media.MIME_TYPE+"=\"image/jpeg\" or "+MediaStore.Images.Media.MIME_TYPE+"=\"image/png\")";
                }
                Cursor cursor1=cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,projection1,selection1,null, MediaStore.Images.Media._ID+" desc");
                if(cursor1.moveToFirst()){
                    int _id=cursor1.getInt(cursor1.getColumnIndex(MediaStore.Images.Media._ID));
                    String[]projectionThumb={MediaStore.Images.Thumbnails.DATA};
                    Cursor cursorprojectionThumb=cr.query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,projectionThumb, MediaStore.Images.Thumbnails.IMAGE_ID+"="+_id+"",null,null);
                    String path=null;
                    if(cursorprojectionThumb.moveToFirst()){
                        //存在缩略图
                        path=cursorprojectionThumb.getString(cursorprojectionThumb.getColumnIndex(MediaStore.Images.Thumbnails.DATA));
                    }
                    if(cursorprojectionThumb!=null){
                        cursorprojectionThumb.close();
                    }
                    String bigPath=cursor1.getString(cursor1.getColumnIndex(MediaStore.Images.Media.DATA));
                    if(TextUtils.isEmpty(path)){
                        path=bigPath;
                    }
                    bucketDisplay.setFirstUrl(path);
                }
                bucketDisplays.add(bucketDisplay);
            }while(cursor.moveToNext());
        }

        return bucketDisplays;
    }
    //获取首张图片作为展示
    private void getFirstImage(ContentResolver cr,BucketDisplay bucketDisplay){
        String[]defaltProjection={MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA};//获取文件夹默认图片信息
        Cursor defaltCursor=cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,defaltProjection, MediaStore.Images.Media.BUCKET_DISPLAY_NAME+"="+bucketDisplay.getName()+"",null, MediaStore.Images.Media._ID+" desc limit 1");
        if(defaltCursor.moveToFirst()){
            int _id=defaltCursor.getInt(defaltCursor.getColumnIndex(MediaStore.Images.Media._COUNT));
            String bigPath = defaltCursor.getString(defaltCursor.getColumnIndex(MediaStore.Images.Media.DATA));//该路径为大图的路径
            String[]projectionThumb={MediaStore.Images.Thumbnails.DATA};
            Cursor cursorprojectionThumb=cr.query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,projectionThumb, MediaStore.Images.Thumbnails.IMAGE_ID+"="+_id,null,null);//获取缩略图地址
            String path=null;
            if(cursorprojectionThumb.moveToFirst()){//存在缩略图
                path=cursorprojectionThumb.getString(cursorprojectionThumb.getColumnIndex(MediaStore.Images.Thumbnails.DATA));
            }
            if(cursorprojectionThumb!=null){
                cursorprojectionThumb.close();
            }
            if(TextUtils.isEmpty(path)){
                path=bigPath;
            }
            bucketDisplay.setFirstUrl(path);
        }
        defaltCursor.close();
    }
}
